//
//  TestExerciseViewController.m
//  Founder_study
//
//  Created by hongbao.cui on 14-11-7.
//  Copyright (c) 2014年 com.founder. All rights reserved.
//

#import "TestExerciseViewController.h"
#import "FMNavgationItem.h"
#import "FMSNetWorkModule.h"
#import "ZipArchive.h"
#import "SynExericisesPaperData.h"
#import "Sqlite.h"
#import "ApplicationUtils.h"
@interface TestExerciseViewController ()

@end

@implementation TestExerciseViewController
@synthesize backBlock;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
//试卷试图的更新
-(void)initTestView:(NSString *)title{
    NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共%d题",title,[self.paperArray count]];
    CGSize size = [paperTitleAndCount sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:CGSizeMake(235, 35) lineBreakMode:NSLineBreakByWordWrapping];
    dispatch_async(dispatch_get_main_queue(), ^{
        [titleLabel setNumberOfLines:0];
        [titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
        [titleLabel setFont:[UIFont systemFontOfSize:13.0]];
        [titleLabel setText:paperTitleAndCount];
        [titleLabel setFrame:CGRectMake(10, (MAX(titleLabel.frame.size.height, 30)-size.height)/2, size.width, size.height)];
        [headerBg setFrame:CGRectMake(0, 0, FMSCREENWIDTH, MAX(titleLabel.frame.size.height, 30))];
        
        NSDictionary *dataDict = [self.paperArray objectAtIndex:0];//更新第一题收藏按钮
        //更新收藏按钮
        NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
        BOOL isCollection = NO;
        if ([favourite_flag isEqualToString:@"1"]) {
            isCollection = YES;
        }
        [collectionBtn setSelected:isCollection];
        [_swipeView reloadData];
        [ApplicationUtils promptRemove];
        
    });
}
-(void)initNetData{
    NSString *urlString = [self.urlDict objectForKey:@"paperFileURL"];
    //    NSString *urlString = @"http://study.yuetong.cn:8080/drappub/rest/mobilestudy/paper/8056?authToken=feixiang0";
    //初始化Documents路径
    NSString *path = FMPAPERSAVE_PATH;//[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Paper"];
    //初始化保存ZIP文件路径
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"paperID"]];
    if ([Sqlite deleteTestQuestionIdAt:paperId]) {//清除试题成功，之后再保存
        FMSCHBLog(@"试题清除成功");
    }else{
        FMSCHBLog(@"试题清除失败!");
    }
    NSString *paperStr = [NSString stringWithFormat:@"paper_%@.zip",paperId];
    NSString *filePath = [path stringByAppendingPathComponent:paperStr];
    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
//    [[FMSNetWorkModule sharedInstance] downloadFatAssFileFrom:urlString toFile:filePath completionCB:^(id result) {
//        if (result == nil) {
//            //初始化ZipArchive
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
//                                                     0), ^{
//                ZipArchive *zip = [[ZipArchive alloc] init];
//                BOOL success = NO;
//                if ([zip UnzipOpenFile:filePath]) {
//                    success = [zip UnzipFileTo:path overWrite:YES];//解压文件
//                    [zip UnzipCloseFile];//关闭
//                    if (!success) {
//                        //解压失败
//                    }else {
//                        //解压成功
                        FMSCHBLog(@"unzip success.............");
                        NSError *error = nil;
//                        NSString *pathStr = [NSString stringWithFormat:@"%@/paper.XML",path];
//                        NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];
                        NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"Paper" ofType:@"xml"];
                        NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];//test
                        if (!error) {
                            SynExericisesPaperData *paperData = [[SynExericisesPaperData alloc] init];
                            NSMutableDictionary *paperDict = [paperData PaperData:paperXmlString];
                            FMSCHBLog(@"paperDict:%@",paperDict);
                            paper_title = [paperDict objectForKey:@"paper_title"];
                            paper_score = [paperDict objectForKey:@"paper_score"];
                            paper_time = [paperDict objectForKey:@"paper_time"];
                            NSMutableArray *array = [paperDict objectForKey:@"questions"];
                            NSMutableArray *questions = [NSMutableArray arrayWithCapacity:1];
                            //                NSMutableArray *array_ = [Sqlite selectTestQuestion:paperId];
                            if (!self.paperArray) {
                                self.paperArray = [NSMutableArray array];
                            }
                            NSInteger number = 0;
                            for (int i=0; i<[array count]; i++) {
                                NSMutableArray *questionArray = [[array objectAtIndex:i] objectForKey:@"question"];
                                NSString *qtype_name =  [[array objectAtIndex:i] objectForKey:@"type_name"];
                                [self.paperArray removeAllObjects];
                                [self.paperArray addObjectsFromArray:questionArray];
                                NSMutableString *answerStr_ = [[NSMutableString alloc] initWithCapacity:1];
                                for (int j=0; j<[self.paperArray count]; j++) {
                                    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:j];
                                    NSString *qtype = [dataDict objectForKey:@"qtype"];
                                    if ([qtype isEqualToString:@"1"]||[qtype isEqualToString:@"2"]) {
                                        [questions addObjectsFromArray:questionArray];
                                        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:paperId,@"paper_id",[dataDict objectForKey:@"questionContent"],@"content",@"1",@"user_error_count",@"0",@"user_right_count",@"0",@"favourite_flag",@"0",@"user_test_sign",[dataDict objectForKey:@"orderid"],@"qst_no",@"",@"user_answer",nil];
                                        [dataDict addEntriesFromDictionary:dict];
                                        NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                        FMSCHBLog(@"cui---hong-------has_sub-----------%@",has_sub);
                                        if (!has_sub) {
                                            has_sub = @"";
                                        }
                                        [dataDict setObject:has_sub forKey:@"has_sub"];
                                        [dataDict setObject:paper_title forKey:@"paper_title"];
                                        [dataDict setObject:paper_score forKey:@"paper_score"];
                                        [dataDict setObject:paper_time forKey:@"paper_time"];
                                        [dataDict setObject:qtype_name forKey:@"qtype_name"];
                                        BOOL success = [Sqlite insertTestQuestion:dataDict];
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        number++;
                                    }else if([qtype isEqualToString:@"3"]){
                                        //判断题
                                        [questions addObjectsFromArray:questionArray];
                                        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:paperId,@"paper_id",[dataDict objectForKey:@"questionContent"],@"content",@"1",@"user_error_count",@"0",@"user_right_count",@"0",@"favourite_flag",@"0",@"user_test_sign",[dataDict objectForKey:@"orderid"],@"qst_no",@"",@"user_answer",nil];
                                        [dataDict addEntriesFromDictionary:dict];
                                        
                                        NSArray  *array = [NSArray arrayWithObjects:@"正确",@"错误",nil];
                                        NSMutableDictionary *optionsDict = [NSMutableDictionary dictionaryWithCapacity:1];
                                        [optionsDict setObject:array forKey:@"options"];
                                        NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                        FMSCHBLog(@"cui---hong-------has_sub-----------%@",has_sub);
                                        if (!has_sub) {
                                            has_sub = @"";
                                        }
                                        [dataDict setObject:has_sub forKey:@"has_sub"];
                                        [dataDict addEntriesFromDictionary:optionsDict];
                                        [dataDict setObject:paper_title forKey:@"paper_title"];
                                        [dataDict setObject:paper_score forKey:@"paper_score"];
                                        [dataDict setObject:paper_time forKey:@"paper_time"];
                                        [dataDict setObject:qtype_name forKey:@"qtype_name"];
                                        BOOL success = [Sqlite insertTestQuestion:dataDict];
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        number++;
                                    }else{//简答题,案例分析题
                                        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:1];
                                        [answerStr_ appendFormat:@"<p>%@</p>",[dataDict objectForKey:@"answer"]];
                                        [dict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:answerStr_ forKey:@"answer"]];
                                        [dict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:[dataDict objectForKey:@"questionContent"] forKey:@"content"]];
                                        [dict setObject:paperId forKey:@"paper_id"];
                                        [dict addEntriesFromDictionary:dataDict];
                                        [dict setObject:@"0" forKey:@"favourite_flag"];
                                        [dict setObject:paper_title forKey:@"paper_title"];
                                        [dict setObject:paper_score forKey:@"paper_score"];
                                        [dict setObject:paper_time forKey:@"paper_time"];
                                        [dict setObject:qtype_name forKey:@"qtype_name"];
                                        BOOL success = [Sqlite insertTestQuestion:dict];
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        [dict removeAllObjects];
                                    }
                                }
                                
                            }
                            NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
                            [self.paperArray removeAllObjects];
                            [self.paperArray addObjectsFromArray:array_afterSave];
                            //                            NSString *paper_title = nil;
                            if ([self.paperArray count]>0) {
                                paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
                            }else{
                                [ApplicationUtils promptRemove];
                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                [alert setTag:4];
                                [alert show];
                                return ;
                            }
                            [self initTestView:paper_title];
                            
                        }
//                    }
//                }else{
//                    FMSCHBLog(@"open fail................");
//                }
//            });
//        }else{
//            [ApplicationUtils promptRemove];
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert setTag:4];
//            [alert show];
//        }
//    }];
    
}
-(void)back{
    [self dismissViewControllerAnimated:YES completion:^{
        [self releaseMyDealloc];
    }];
    if (self.backBlock) {
        self.backBlock();
    }
}
-(void)initItem{
    self.navigationItem.title = @"试卷练习";

    FMNavgationItem* leftItem = [[FMNavgationItem alloc] init];
    [leftItem.backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems = [leftItem getNavgationItemWithType:WRNavgationTypeLeft Ima:[ApplicationUtils getLocalImage:@"Navigation-Bar_Return_btn_@2x"] ImaHighlight:[ApplicationUtils getLocalImage:@"Navigation-Bar_Return_btn_@2x"] title:@""];
}
-(void)initData{
    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"paperID"]];
    NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
    if (!self.paperArray) {
        self.paperArray = [NSMutableArray arrayWithCapacity:1];
    }
    [self.paperArray addObjectsFromArray:array_afterSave];//存为全局，以后使用
    paper_title = nil;
    paper_score = nil;
    paper_time = nil;
    if ([self.paperArray count]>0) {
        paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
        paper_score = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_score"];
        paper_time = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_time"];
        [self initTestView:paper_title];
    }else{
        [self initNetData];
    }
}
- (void)viewDidLoad
{
    isExercise = YES;//设置是测试模式还是练习模式
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initItem];
    [self initData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)releaseMyDealloc{
    [[FMSNetWorkModule sharedInstance] cancleAllOperation];
}
-(void)dealloc{
    if (self.backBlock) {
        self.backBlock = nil;
    }
    [self releaseMyDealloc];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
